package com.more.spring.boot.springbootredisdemo.controller;

import com.more.spring.boot.springbootredisdemo.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class SessionController {

    /**
     * 登录系统
     * @param username password
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/session/login", method = RequestMethod.GET)
    public Map login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request, HttpSession session){
        String message = "login failure";
        HashMap<String, Object> resultMap = new HashMap<>();
        if (username != null && password != null && "xinping".equals(username) && "123".equals(password)) {
            User tempUser = new User();
            tempUser.setName(username);
            tempUser.setPassword(password);
            request.getSession().setAttribute("admin", tempUser);
            message = "login success";
            resultMap.put("message", message);
            resultMap.put("sessionId", session.getId());
        }else {
            resultMap.put("message", message);
        }
        return resultMap;
    }

    @RequestMapping(value = "session/get", method = RequestMethod.GET)
    @ResponseBody
    public Map get(@RequestParam("username") String username, HttpServletRequest request, HttpSession session){
        User user = (User) request.getSession().getAttribute("admin");
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("message", user);
        resultMap.put("sessionId", session.getId());
        return resultMap;
    }
}
